#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        for (int i = 0; i < nums.size(); i++) {
            for (int j = i + 1; j < nums.size(); j++) {
                if (nums[i] == nums[j]) {
                    if (abs(i - j) <= k)return true;
                }
            }
        }
        return false;
    }
};
class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int, int> numtoindex;
        for (int i = 0; i < nums.size(); i++) {
            if (numtoindex.find(nums[i]) != numtoindex.end()) {
                if (i - numtoindex[nums[i]] <= k)return true;
            }
            numtoindex[nums[i]] = i;
        }
        return false;
    }
};